package com.jwell.panrank.presenter

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.jwell.driverapp.tools.BaseSubscriber
import com.jwell.driverapp.ui.base.BasePresenter
import com.jwell.panrank.contract.MainContract
import com.jwell.panrank.entity.MeasurePlace
import com.jwell.panrank.entity.UnLoadingPointBean
import com.jwell.panrank.model.MainModel
import com.jwell.panrank.tools.DataModel
import org.json.JSONObject
import org.reactivestreams.Subscription

/**
 * Created by 76577 on 2018/5/8.
 * 首页
 */
class MainPresenter : MainContract.Presenter, BasePresenter<MainContract.View>() {


    private val model by lazy {
        MainModel()
    }

    override fun checkPermission() {
        model.checkPermission(object : BaseSubscriber() {
            override fun setSubscription(s: Subscription) {
                mSubscription = s
            }

            override fun succeed(data: JSONObject) {
                val permission = Gson().fromJson<List<String>>(data.getString("result"), object : TypeToken<List<String>>() {
                }.type)
                DataModel.getInstance().savePermission(permission)
                getView()?.setPermission()
            }

            override fun onFailed(msg: String) {

            }
        })
    }

    override fun getUnloadingPoint() {
        model.getUnloadingPoint(object : BaseSubscriber() {
            override fun setSubscription(s: Subscription) {
                mSubscription = s
            }

            override fun succeed(data: JSONObject) {
                val permission = Gson().fromJson<List<UnLoadingPointBean>>(data.getString("result"), object : TypeToken<List<UnLoadingPointBean>>() {
                }.type)
                println("收料点的大小" + permission.size)
                if (permission.isNotEmpty()) {
                    DataModel.getInstance().saveUnloadingPoint(permission)
                }
            }

            override fun onFailed(msg: String) {

            }
        })
    }

    override fun getMeasurePlaceList() {
        model.getMeasurePlaceList(object : BaseSubscriber() {
            override fun setSubscription(s: Subscription) {
                mSubscription = s
            }

            override fun succeed(data: JSONObject) {
                val permission = Gson().fromJson<List<MeasurePlace>>(data.getString("result"), object : TypeToken<List<MeasurePlace>>() {
                }.type)
                println("计量点的大小" + permission.size)
                if (permission.isNotEmpty()) {
                    DataModel.getInstance().saveMeasurePlace(permission)
                }
            }

            override fun onFailed(msg: String) {
            }
        })
    }

}